package top.wilsonlv.jaguar.cloud.auth.config;

import groovy.lang.GroovyClassLoader;
import lombok.RequiredArgsConstructor;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AccountStatusUserDetailsChecker;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import org.springframework.session.data.redis.RedisIndexedSessionRepository;
import org.springframework.session.security.SpringSessionBackedSessionRegistry;

import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * @author lvws
 * @since 2022/8/18
 */
@Configuration
@RequiredArgsConstructor
public class AuthServerBeanConfiguration {

    private final RedisIndexedSessionRepository redisIndexedSessionRepository;

    @Bean
    public UserDetailsChecker userDetailsChecker() {
        return new AccountStatusUserDetailsChecker();
    }

    @Bean
    public SpringSessionBackedSessionRegistry<?> redisSessionRegistry() {
        return new SpringSessionBackedSessionRegistry<>(redisIndexedSessionRepository);
    }

    @Bean
    public TokenStore tokenStore(RedisConnectionFactory redisConnectionFactory) {
        RedisTokenStore redisTokenStore = new RedisTokenStore(redisConnectionFactory);
        redisTokenStore.setPrefix("oauth2:");
        return redisTokenStore;
    }

    @Bean
    public GroovyClassLoader groovyClassLoader() {
        return new GroovyClassLoader();
    }

    @Bean
    public VelocityEngine velocityEngine() {
        Properties properties = new Properties();
        properties.setProperty("resource.loader.file.class", ClasspathResourceLoader.class.getName());
        properties.setProperty(Velocity.INPUT_ENCODING, StandardCharsets.UTF_8.name());

        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init(properties);
        return velocityEngine;
    }

}
